<template>
  <el-button link class="default" @click="toggleSortOrder">
    {{ label }}
    <span style="display: flex;flex-direction: column;">
      <CaretTop style="width: 1em;height: 0.857em;margin-bottom: -3px;"
        :style="sortStatus === 'asc' ? 'color: var(--jbc-color)' : ''" />
      <CaretBottom style="width: 1em;height: 0.857em;margin-top: -3px;"
        :style="sortStatus === 'desc' ? 'color: var(--jbc-color)' : ''" />
    </span>
  </el-button>
</template>

<script setup name="sortButton">
import { CaretTop, CaretBottom } from '@element-plus/icons-vue'

const props = defineProps({
  label: {
    type: String,
    default: 'Sort',
  },
  property: {
    type: String,
    required: true,
    default: ''
  }
})
const emit = defineEmits(['sort'])
// 定义排序状态，默认为升序
const isAscending = ref(true);
// 是否
const isShow = ref(false);
// 根据排序状态返回对应的图标
const sortStatus = computed(() => {
  return isShow.value && isAscending.value ? 'asc' : isShow.value && !isAscending.value ? 'desc' : '';
});

// 切换排序状态的方法
const toggleSortOrder = () => {
  if (isShow.value) {
    if (isAscending.value) {
      isAscending.value = false
    } else {
      isShow.value = false
    }
  } else {
    isShow.value = true
    isAscending.value = true
  }
  emit('sort', {
    property: props.property,
    order: isShow.value && isAscending.value ? 'asc' : isShow.value && !isAscending.value ? 'desc' : ''
  })
};
defineExpose({
  setDefault: () => {
    isShow.value = false
    isAscending.value = true
  }
})
</script>

<style scoped>
.el-button--default {
  --el-button-bg-color: var(--jbc-font-color-light);
  --el-button-text-color: var(--jbc-font-color-light);
  --el-button-border-color: var(--jbc-font-color-light);
}
</style>